/*
* This software is licensed under the GNU General Public License, version 2
* You may copy, distribute and modify the software as long as you track changes/dates of in source files and keep all modifications under GPL. You can distribute your application using a GPL library commercially, but you must also provide the source code.

* DNNspot Software (http://www.dnnspot.com)
* Copyright (C) 2013 Atriage Software LLC
* Authors: Kevin Southworth, Matthew Hall, Ryan Doom

* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.

* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.

* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

* Full license viewable here: http://www.gnu.org/licenses/gpl-2.0.txt
*/

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

using DNNspot.LiveChat.DataModel;
using DotNetNuke.Common;
using DotNetNuke.Entities.Host;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Portals;
using DotNetNuke.Entities.Users;
using EntitySpaces.Interfaces;

namespace DNNspot.LiveChat
{
    public partial class LiveChat : PortalModuleBase
    {
        private int PortalId = PortalController.GetCurrentPortalSettings().PortalId;

        public string ModuleWebPath
        {
            get
            {
                var portalId = PortalController.GetCurrentPortalSettings().PortalId;
                var module = new ModuleController().GetModuleByDefinition(portalId, ModuleSettings.FolderName);

                return String.Format("/DesktopModules/{0}/", module != null ? module.FolderName : ModuleSettings.FolderName);
            }
        }

        // ### EVENTS ######################################################

        protected void Page_Init(object sender, EventArgs e)
        {
            InitializeProvider();
        }

        protected void Page_PreRender(object sender, EventArgs e)
        {
            IncludeJS();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            AgentCollection.RemoveAllInactive(90);
            SetChatLink();
        }

        // ### PRIVATE FUNCTIONS ###########################################

        private void IncludeJS()
        {
            //if (string.IsNullOrEmpty(HostSettings.GetHostSetting(ModuleSettings.NoJQuery)) && HttpContext.Current.Items["jquery_registered"] == null)
            //{
            //    RegisterJavascript(String.Format("{0}{1}js/jquery-1.3.1.min.js", Globals.ApplicationPath, ModuleWebPath));
            //    HttpContext.Current.Items.Add("jquery_registered", "true");
            //}

            RegisterJavascript(string.Format("{0}{1}js/dnnspot.livechat.include.js", Globals.ApplicationPath, ModuleWebPath));
        }

        private static void InitializeProvider()
        {
            if (esConfigSettings.ConnectionInfo.Default != "SiteSqlServer")
            {
                esConfigSettings connectionInfoSettings = esConfigSettings.ConnectionInfo;
                foreach (esConnectionElement connection in connectionInfoSettings.Connections)
                {
                    //if there is a SiteSqlServer in es connections set it default
                    if (connection.Name == "SiteSqlServer")
                    {
                        esConfigSettings.ConnectionInfo.Default = connection.Name;
                        return;
                    }
                }

                //no SiteSqlServer found grab dnn cnn string and create
                string dnnConnection = ConfigurationManager.ConnectionStrings["SiteSqlServer"].ConnectionString;

                // Manually register a connection
                esConnectionElement conn = new esConnectionElement();
                conn.ConnectionString = dnnConnection;
                conn.Name = "SiteSqlServer";
                conn.Provider = "EntitySpaces.SqlClientProvider";
                conn.ProviderClass = "DataProvider";
                conn.SqlAccessType = esSqlAccessType.DynamicSQL;
                conn.ProviderMetadataKey = "esDefault";
                conn.DatabaseVersion = "2005";

                // Assign the Default Connection
                esConfigSettings.ConnectionInfo.Connections.Add(conn);
                esConfigSettings.ConnectionInfo.Default = "SiteSqlServer";

                // Register the Loader
                esProviderFactory.Factory = new EntitySpaces.LoaderMT.esDataProviderFactory();
            }
        }

        protected void RegisterJavascript(string fullPath)
        {
            var script = new HtmlGenericControl("script");
            script.Attributes.Add("type", "text/javascript");
            script.Attributes.Add("src", fullPath);

            Page.Header.Controls.Add(script);
        }

        private void SetChatLink()
        {
            if (Agent.IsAgent(UserController.GetCurrentUserInfo().UserID) || AgentCollection.AgentIsAvailable(PortalId))
            {
                var page = "ClientChat.aspx";
                var height = 400;
                var width = 450;

                if (Agent.IsAgent(UserController.GetCurrentUserInfo().UserID))
                {
                    page = "AgentChat.aspx";
                    height = 450;
                    width = 900;
                }
                page += "?mid=" + ModuleId;

                lnkChat.Text = PortalSetting.Get(PortalId, PortalSettingNames.ChatOnlineMessage) ?? "Live Chat";
                lnkChat.NavigateUrl = string.Format("{0}{1}", ModuleWebPath, page);
                lnkChat.CssClass += " online";

                hidHeight.Value = height.ToString();
                hidWidth.Value = width.ToString();
            }
            else
            {
                lnkChat.Text = PortalSetting.Get(PortalId, PortalSettingNames.ChatOfflineMessage) ?? "Live Chat Offline";
                lnkChat.CssClass += " offline";
            }
        }
    }
}